package models

import (
	fn "OAM/util"
	"time"
)

type TreeGridNode[T HostTreeGridNode] struct {
	Id       int
	Text     string
	State    string
	Children []*T `json:",omitempty"`
}

type HostTreeGridNode struct {
	TreeGridNode[HostTreeGridNode]
	OriginalId int
	Uri        string
	Port       int `json:",omitempty"`
	Desc       string
	Type       uint8
	CreateTime time.Time
}

const (
	state_open  = "open"
	state_close = "closed"
)

func (parent *HostTreeGridNode) AddNode(child *HostTreeGridNode) {
	var baseId = parent.Id
	if baseId == 0 {
		baseId = 1
	}
	if len(parent.Children) == 0 {
		child.Id = baseId * 10 //生成一个唯一ID,不用数据库中ID,因为hostId,AppId可能重复,导致treegrid行无法选中
		children := []*HostTreeGridNode{child}
		parent.Children = children
	} else {
		child.Id = baseId*10 + len(parent.Children) + 1
		parent.Children = append(parent.Children, child)
	}
}

func (parent HostTreeGridNode) GetChild(originalId int) *HostTreeGridNode {
	for _, node := range parent.Children {
		if node.OriginalId == originalId {
			return node
		}
	}
	return nil
}

func (parent *HostTreeGridNode) AddHostNode(child Host) *HostTreeGridNode {
	uri := fn.JoinStr("/", child.PublicIp, child.InternalIp)
	if uri[0] == '/' {
		uri = uri[1:]
	}
	childNode := HostTreeGridNode{
		TreeGridNode: TreeGridNode[HostTreeGridNode]{Text: child.HostName, State: state_open},
		OriginalId:   child.HostId,
		Uri:          uri,
		Port:         child.SshPort,
		CreateTime:   child.CreateTime,
		Type:         0,
	}
	/* if child.ServiceSoftwares != "" {
		childNode.Desc = "已安装软件:" + child.ServiceSoftwares
	} */
	parent.AddNode(&childNode)
	return &childNode
}

func (parent *HostTreeGridNode) AddAppNode(child AppInfo) *HostTreeGridNode {
	childNode := HostTreeGridNode{
		TreeGridNode: TreeGridNode[HostTreeGridNode]{Text: child.AppName},
		OriginalId:   child.AppId,
		Uri:          child.AppDir,
		Port:         child.AppPort,
		CreateTime:   child.CreateTime,
		Type:         1,
	}
	if child.AppUrl != "" {
		childNode.Desc = "访问地址:" + child.AppUrl
	}
	parent.AddNode(&childNode)
	return &childNode
}
